﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Text;
using App.Models;
using App.Models.Pager;
using App.Views.ViewModels;

namespace App.Controllers
{
    public class RegistrationInfoController : BaseController
    {
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult List(int? page, int? rows, string order)
        {
            dbe.ContextOptions.ProxyCreationEnabled = false;
            dbe.ContextOptions.LazyLoadingEnabled = false;

            int offset = (page ?? 1 - 1) * (rows ?? 10);
            PagedList<tb_RegistrationInfo> list = null;
            if ("asc" == order)
            {
                list = dbe.tb_RegistrationInfo.OrderBy(m => m.DeadNO)
                                .ToPagedList(page ?? 1, rows ?? 10);
            }
            else
            {
                list = dbe.tb_RegistrationInfo.OrderByDescending(m => m.DeadNO)
                                .ToPagedList(page ?? 1, rows ?? 10);
            }

            return Json(list, JsonRequestBehavior.AllowGet);
        }
        
        public ActionResult Create() {
            var vmodel = new RegistrationInfoViewModel
            {
                DeadNO = GenDeadNO(),
                BurialMode = "火葬",
                DeadCity = "伊宁市"
            };
            var cityList = dbe.tb_City.ToList();
            ViewData["cityList"] = cityList;
            return View(vmodel);
        }

        [HttpPost]
        public ActionResult Create(RegistrationInfoViewModel vmodel)
        {
            try {
                if (!ModelState.IsValid) {
                    throw new Exception("模型有误！");
                }
                var model = new tb_RegistrationInfo
                {
                    DeadNO = vmodel.DeadNO,
                    DeadName = vmodel.DeadName,
                    DeadIDCard = vmodel.DeadIDCard,
                    DeadNation = vmodel.DeadNation,
                    DeadAge = vmodel.DeadAge,
                    DeadCity = vmodel.DeadCity,
                    BurialMode = vmodel.BurialMode,
                    DeadPlace = vmodel.DeadPlace,
                    DeadSex = vmodel.DeadSex,
                    DeadReason = vmodel.DeadReason,
                    DeadTime = vmodel.DeadTime,
                    WorkUnit = vmodel.WorkUnit,
                    LifetimeJob = vmodel.LifetimeJob,
                    Residence = vmodel.Residence,

                    FamilyName = vmodel.FamilyName,
                    FamilyIDCard = vmodel.FamilyIDCard,
                    FamilyPhone = vmodel.FamilyPhone,
                    FamilyPostcode = vmodel.FamilyPostcode,
                    FamilyAddress = vmodel.FamilyAddress,
                    FamilyRelationship = vmodel.FamilyRelationship,

                    Appendix1 = vmodel.Appendix1,
                    Appendix2 = vmodel.Appendix2,
                    Appendix3 = vmodel.Appendix3,
                    Appendix4 = vmodel.Appendix4,

                    RegistDate = DateTime.Now
                };
                dbe.tb_RegistrationInfo.AddObject(model);
                dbe.SaveChanges();
                var res = new { success = true, msg = model };
                return Json(res, JsonRequestBehavior.AllowGet);
            }
            catch {
                ModelState.AddModelError("ERRMSG", "保存出错");
                var cityList = dbe.tb_City.ToList();
                ViewData["cityList"] = cityList;
                return PartialView("UCRegistrationInfoEdit", vmodel);
            }            
        }

        public ActionResult Edit(string id)
        {
            var model = dbe.tb_RegistrationInfo.FirstOrDefault(m=>m.DeadNO == id);
            var vmodel = new RegistrationInfoViewModel 
            {
                DeadNO = model.DeadNO,
                DeadName = model.DeadName,
                DeadIDCard = model.DeadIDCard,
                DeadNation = model.DeadNation,
                DeadCity = model.DeadCity,
                BurialMode = model.BurialMode,
                DeadAge = model.DeadAge,
                DeadPlace = model.DeadPlace,
                DeadSex = model.DeadSex,
                DeadReason = model.DeadReason,
                DeadTime = model.DeadTime,
                WorkUnit = model.WorkUnit,
                LifetimeJob = model.LifetimeJob,
                Residence = model.Residence,

                FamilyName = model.FamilyName,
                FamilyIDCard = model.FamilyIDCard,
                FamilyPhone = model.FamilyPhone,
                FamilyPostcode = model.FamilyPostcode,
                FamilyAddress = model.FamilyAddress,
                FamilyRelationship = model.FamilyRelationship,

                Appendix1 = model.Appendix1,
                Appendix2 = model.Appendix2,
                Appendix3 = model.Appendix3,
                Appendix4 = model.Appendix4
            };
            var cityList = dbe.tb_City.ToList();
            ViewData["cityList"] = cityList;
            return View(vmodel);
        }
        [HttpPost]
        public ActionResult Edit(string id, RegistrationInfoViewModel vmodel)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    throw new Exception("模型有误！");
                }
                var model = dbe.tb_RegistrationInfo.FirstOrDefault(m => m.DeadNO == id);

                model.DeadName = vmodel.DeadName;
                model.DeadIDCard = vmodel.DeadIDCard;
                model.DeadNation = vmodel.DeadNation;
                model.DeadCity = vmodel.DeadCity;
                model.BurialMode = vmodel.BurialMode;
                model.DeadAge = vmodel.DeadAge;
                model.DeadPlace = vmodel.DeadPlace;
                model.DeadSex = vmodel.DeadSex;
                model.DeadReason = vmodel.DeadReason;
                model.DeadTime = vmodel.DeadTime;
                model.WorkUnit = vmodel.WorkUnit;
                model.LifetimeJob = vmodel.LifetimeJob;
                model.Residence = vmodel.Residence;

                model.FamilyName = vmodel.FamilyName;
                model.FamilyIDCard = vmodel.FamilyIDCard;
                model.FamilyPhone = vmodel.FamilyPhone;
                model.FamilyPostcode = vmodel.FamilyPostcode;
                model.FamilyAddress = vmodel.FamilyAddress;
                model.FamilyRelationship = vmodel.FamilyRelationship;

                model.Appendix1 = vmodel.Appendix1;
                model.Appendix2 = vmodel.Appendix2;
                model.Appendix3 = vmodel.Appendix3;
                model.Appendix4 = vmodel.Appendix4;
                dbe.SaveChanges();
                CurrentDeader = vmodel.DeadNO;
                var res = new { success = true, msg = model };
                return Json(res, JsonRequestBehavior.AllowGet); 
            }
            catch {
                ModelState.AddModelError("ERRMSG", "保存出错");
                var cityList = dbe.tb_City.ToList();
                ViewData["cityList"] = cityList;
                return PartialView("UCRegistrationInfoEdit", vmodel);
            }   
        }
        public ActionResult Delete(string ids)
        {
            try
            {
                string[] idList = ids.Split('&');
                foreach (var id in idList)
                {
                    var obj = dbe.tb_RegistrationInfo.FirstOrDefault(m => m.DeadNO == id);
                    dbe.tb_RegistrationInfo.DeleteObject(obj);
                }

                dbe.SaveChanges();
                var res = new { success = true };
                return Json(res, JsonRequestBehavior.AllowGet);
            }
            catch
            {
                var res = new { success = false, msg = "删除出错！" };
                return Json(res, JsonRequestBehavior.AllowGet);
            }
        }
        public ActionResult UploadFile(string id)
        {
            HttpPostedFileBase uploadFile = Request.Files["uploadFile"];
            string path = AppDomain.CurrentDomain.BaseDirectory + "/uploads/";
            string ufile = uploadFile.FileName;
            string ext = ufile.Substring(ufile.LastIndexOf('.'));
            string filename = Path.GetFileName(id + ext);
            uploadFile.SaveAs(Path.Combine(path, filename));            
            return Content(id+ext);
        }
        //选择死者编号，最近2个月的
        public ActionResult SelectDeadNo() { 
            DateTime dt = DateTime.Now;
            dt = dt.AddMonths(-2);
            var deads = dbe.tb_RegistrationInfo.Where(m=>m.DeadTime== null || (m.DeadTime.Value >= dt));
            return PartialView(deads);
        }

        public ActionResult AutoSelectDeadNo(string q) {
            //禁止页面被缓存
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetExpires(DateTime.Today.AddYears(-2));

            var list = dbe.tb_RegistrationInfo.Where(m => m.DeadNO.StartsWith(q));            
            StringBuilder txt = new StringBuilder();
            foreach (var o in list) {
                txt.AppendLine(o.DeadNO + "|" + o.DeadName);
            }
            return Content(txt.ToString());
        }
    }
}
